<?php


namespace app\common\model;


use think\Db;

class ProductStock extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_products_stock';
    // 主键ID
    protected $pk = 'p_s_id';

    /**
     * @param array $where  // 查询的条件
     * @param string $item  // 查询的参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
//    商品减少库存
    function reducestock($product_id,$p_s_id,$number){
        $condition = [
            "p_s_id" => $p_s_id,
            "product_id" => $product_id,
        ];
        $rs = $this
            ->where($condition)
            ->setDec('stock',$number);
        return $rs;
    }

    function getOneStock($product_id,$stock_id,$item = '*'){
        $where = [
            ["product_id",'=',$product_id],
            ["p_s_id",'=',$stock_id],
        ];
        $rs = $this
            ->where($where)
            ->field($item)
            ->find();
        return $rs;
    }

    function get_stock_list($condition,$item = '*',$orderby = "p_s_id desc"){
        $where = null;
        if(!empty($condition['product_id'])){
            $where[] = ['product_id','=',$condition['product_id']];
        }
        if(!empty($condition['stock_id'])){
            $where[] = ['stock_id','=',$condition['stock_id']];
        }
        if(!empty($condition['is_del'])){
            $where[] = ['is_del','=',$condition['is_del']];
        }
        $rs = $this
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->select();
        return $rs;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ['p_s_id' => $id];
            $params['update_time'] = time();
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            // 新增数据
            $params['add_time'] = time();
            $this->allowField(true)->save($params);
            $rs = $this->p_s_id;
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

    // 批量更新库存
    function batchstock($params,$method = '+'){
        $mysql = "update {$this->table} set stock = case {$this->pk} ";
        foreach($params as $key => $value){
            $data[] = $value['p_s_id'];
            $mysql .= " when {$value['p_s_id']} then `stock` {$method} ".$value['quantity'];
        }
        $mysql .= " end where {$this->pk} in (".implode(",",$data).")";
        $rs = $this->execute($mysql);
        if(!$rs){
            $this->setError(-1,'批量更新操作失败');
            return false;
        }
        return true;
    }
}